<?php

namespace common\models;

use common\Service\RedisService;
use Yii;

/**
 * This is the model class for table "{{%tags}}".
 *
 * @property string $id
 * @property string $name
 * @property string $show_name
 * @property string $alias
 * @property string $tags
 * @property integer $type
 * @property string $sort
 * @property integer $status
 */
class Tags extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%tags}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['type', 'sort', 'status','category','click_num'], 'integer'],
            [['name', 'show_name', 'alias'], 'string', 'max' => 30],
            [['tags'], 'string', 'max' => 80],
            [['name'], 'unique'],
            [['alias'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '标签名字',
            'show_name' => '展示标签名字',
            'alias' => '别名',
            'tags' => '下级标签',
            'type' => '类别 0：默认常规标签 1：国家 2：类型（性感，气质，清纯，可爱等）3：职业 5：星座',
            'sort' => '排序（权重）',
            'status' => '状态　１：正常　２：下架',
        ];
    }


    /*
     *
     * mv:列表页面展示标签 分类别=》国家 类型 职业 星座 常规
     * 1：国家固定
     * 0 2 3：取最热的类型标签固定个数 每天自动脚本更新点击到数据库  前端直接数据库做缓存 套路一致
     * 4：星座固定
     *
     */


    /**
     * @desc 解析标签的详细信息
     * @param $tags
     * @param $indexBy
     * @return array
     */
    public function parseTags($tags,$indexBy = ''){
        $rs = [];
        is_string($tags) && $tags = explode('-',$tags);
        if(!empty($tags)){
            foreach ($tags as $alias){
                if(!empty($alias) && $temp = static::tagInfoByAlias($alias)){
                    empty($indexBy) ? $rs[] = $temp : $rs[$temp[$indexBy]] = $temp;
                }
            }
        }


        return $rs;
    }

    public static function formatTag($id,$tagInfo = []){
        $id = intval($id);
        if($id > 0){
            empty($tagInfo) && $tagInfo = RedisService::getHash('tag:'.$id);
//            isset($tagInfo['show_name']) && !empty($tagInfo['show_name']) && $tagInfo['name'] = trim($tagInfo['show_name']);
            if(!empty($tagInfo)){
                (!isset($tagInfo['show_name']) || empty($tagInfo['show_name'])) && $tagInfo['show_name'] = trim($tagInfo['name']);
            }

        }
        return $tagInfo;
    }


    /**
     * @desc 根据标签缩写获取标签信息
     * @param string $alias
     * @return array
     */
    public static function tagInfoByAlias($alias = ''){
        //TODO 后面修改成从redis读取数据
        //return Tags::find()->where(['alias' => trim($alias)])->asArray()->one();
        $id = (int)Yii::$app->get('redis')->HGet('tagAliasId',trim($alias));
        return static::formatTag($id);
    }

    public static function tagInfoByName($name = ''){
        $id = (int)Yii::$app->get('redis')->HGet('tagNameId',trim($name));
        return static::formatTag($id);
    }

    public static function tagInfoById($id = 0){
//        return Tags::find()->where(['id' => intval($id)])->asArray()->one();
        return static::formatTag($id);
    }



    /*
     * 初始化标签信息到redis
     */
    public function setRedis(){
        $allTags = Tags::find()->all();
        $allTagsArr = [];
        foreach ($allTags as $tag){
            $tag->loadDefaultValues();
            RedisService::setHash('tag:'.intval($tag['id']),$tag->attributes);
            $allTagsArr[] = $tag->attributes;
        }
        RedisService::setHash('tagAliasId',array_column($allTagsArr,'id','alias'));
        RedisService::setHash('tagNameId',array_column($allTagsArr,'id','name'));
        echo 'ok';exit;
    }



    public static function parseTagsByName($tags, $indexBy = '')
    {
        $rs = [];
        if(empty($tags)) return $rs;

        if(is_string($tags)){
            $tags = str_replace(['-','，','、','、'],',',$tags);
            $tags = explode(',',$tags);
        }

        if(!empty($tags)){
            foreach ($tags as $name){
                if(!empty($name) && $temp = static::tagInfoByName($name)){
                    empty($indexBy) ? $rs[] = $temp : $rs[$temp[$indexBy]] = $temp;
                }
            }
        }

        return $rs;
    }

    /*
     * 随机获取标签  排名10-200的标签
     */
    public static function randTags($limit = 10){
        $tagAlias = Yii::$app->get('redis')->zrevrange('tagZset',10,200);
        $tagAliasIndex = array_rand($tagAlias,$limit);

        $rs = [];
        foreach($tagAliasIndex as $index){
            $tmp = static::tagInfoByAlias($tagAlias[$index]);
            !empty($tmp) && $rs[] = $tmp;
        }

        return $rs;
    }
}
